/*
 * GameField.java
 *
 * Created on 31 juli 2006, 0:42
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package be.drapier;

/**
 *
 * @author Wim Drapier
 */
public class GameField {
    
    private final byte FIELD = 0;
    private final byte PLAYER = 1;
    private final byte START_PIPE = 2;
    private final byte END_PIPE = 3;

    // Move directions
    public static final int LEFT = 0;
    public static final int RIGHT = 3;
    public static final int UP = 1;
    public static final int DOWN = 2;
    
    private int cols, rows;
    private byte[] fields;

    
    private int selectedField;
    
    /** Creates a new instance of GameField */
    public GameField(int cols, int rows) {
        this.cols = cols;
        this.rows = rows;
        fields = new byte[cols * rows];
        
        selectedField = index(2,3);
    }
    
    private int index(int x, int y) {
        if(x < 0 || x >= cols || y < 0 || y >= rows)
            return -1;
        return y * cols + x;
    }
    
    /**
     * Compute the offset in the array of the cell relative
     * to the current field that is active in the direction of the move.
     */
    public int getSelectedField() {
        int x = selectedField % getCols();
	int y = selectedField / getCols();
	return (y << 16) + x;
    }

    public int getCols() {
        return cols;
    }

    public int getRows() {
        return rows;
    }

    int move(int move) {
        switch (move) {
            case UP :
                selectedField -= cols;
                if (selectedField == -cols) {
                    selectedField = fields.length - 1;
                } else if (selectedField < 0 )  {
                    selectedField += fields.length - 1;
                }
                break;
            case DOWN : 
                selectedField += cols;
                if (selectedField == (fields.length + cols - 1)) {
                    selectedField = 0;
                } else if (selectedField > fields.length - 1) {
                    selectedField -= fields.length - 1;
                }
                break;
            case LEFT : 
                selectedField--;
                if (selectedField < 0) {
                    selectedField = fields.length - 1;
                }
                break;
            case RIGHT : 
                selectedField++;
                if(selectedField == fields.length)
                    selectedField = 0;
                break;
        }
        return 0;
    }
}
